<!DOCTYPE html><html lang="zh-Hans"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"><meta name="description" content="iOS谓词NSPredicate 筛选过滤"><meta name="keywords" content="iOS"><meta name="author" content="kyren"><meta name="copyright" content="kyren"><title>iOS谓词NSPredicate 筛选过滤 | Kyren's Blog</title><link rel="shortcut icon" href="/melody-favicon.ico"><link rel="stylesheet" href="/css/index.css?version=1.9.0"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@latest/css/font-awesome.min.css?version=1.9.0"><meta name="format-detection" content="telephone=no"><meta http-equiv="x-dns-prefetch-control" content="on"><link rel="dns-prefetch" href="https://cdn.jsdelivr.net"><link rel="dns-prefetch" href="https://hm.baidu.com"><script>var _hmt = _hmt || [];
(function() {
  var hm = document.createElement("script");
  hm.src = "https://hm.baidu.com/hm.js?cf87fcdbd9ab7cf93d894f7c219ae78f";
  var s = document.getElementsByTagName("script")[0]; 
  s.parentNode.insertBefore(hm, s);
})();</script><meta http-equiv="Cache-Control" content="no-transform"><meta http-equiv="Cache-Control" content="no-siteapp"><script src="https://v1.hitokoto.cn/?encode=js&amp;charset=utf-8&amp;select=.footer_custom_text" defer></script><script>var GLOBAL_CONFIG = { 
  root: '/',
  algolia: undefined,
  localSearch: {"path":"search.xml","languages":{"hits_empty":"找不到您查询的内容:${query}"}},
  copy: {
    success: '复制成功',
    error: '复制错误',
    noSupport: '浏览器不支持'
  },
  hexoVersion: '6.2.0'
} </script><meta name="generator" content="Hexo 6.2.0"></head><body><i class="fa fa-arrow-right" id="toggle-sidebar" aria-hidden="true"></i><div id="sidebar" data-display="true"><div class="toggle-sidebar-info text-center"><span data-toggle="切换文章详情">切换站点概览</span><hr></div><div class="sidebar-toc"><div class="sidebar-toc__title">目录</div><div class="sidebar-toc__progress"><span class="progress-notice">你已经读了</span><span class="progress-num">0</span><span class="progress-percentage">%</span><div class="sidebar-toc__progress-bar"></div></div><div class="sidebar-toc__content"><ol class="toc"><li class="toc-item toc-level-5"><a class="toc-link" href="#1-%E6%AF%94%E8%BE%83%E8%BF%90%E7%AE%97%E7%AC%A6-gt-lt-x3D-x3D-gt-x3D-lt-x3D-x3D"><span class="toc-number">1.</span> <span class="toc-text">1.比较运算符(&gt;,&lt;,&#x3D;&#x3D;,&gt;&#x3D;,&lt;&#x3D;,!&#x3D;)</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#2%E3%80%81%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">2.</span> <span class="toc-text">2、运算符</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#%E6%AF%94%E8%BE%83%E5%92%8C%E9%80%BB%E8%BE%91%E8%BF%90%E7%AE%97%E7%AC%A6"><span class="toc-number">3.</span> <span class="toc-text">比较和逻辑运算符</span></a><ol class="toc-child"><li class="toc-item toc-level-6"><a class="toc-link" href="#2-1-%E8%8C%83%E5%9B%B4%E8%BF%90%E7%AE%97%E7%AC%A6-IN%E3%80%81BETWEEN"><span class="toc-number">3.1.</span> <span class="toc-text">2.1.范围运算符(IN、BETWEEN)</span></a></li></ol></li><li class="toc-item toc-level-5"><a class="toc-link" href="#3-%E5%AD%97%E7%AC%A6%E4%B8%B2%E6%9C%AC%E8%BA%AB-SELF"><span class="toc-number">4.</span> <span class="toc-text">3.字符串本身(SELF)</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#4%E5%AD%97%E7%AC%A6%E4%B8%B2%E7%9B%B8%E5%85%B3%EF%BC%88BEGINSWITH%E3%80%81ENDSWITH%E3%80%81CONTAINS%EF%BC%89"><span class="toc-number">5.</span> <span class="toc-text">4字符串相关（BEGINSWITH、ENDSWITH、CONTAINS）</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#5%E9%80%9A%E9%85%8D%E7%AC%A6%EF%BC%9ALIKE"><span class="toc-number">6.</span> <span class="toc-text">5通配符：LIKE</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#6%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F"><span class="toc-number">7.</span> <span class="toc-text">6正则表达式</span></a></li></ol></div></div><div class="author-info hide"><div class="author-info__avatar text-center"><img src="https://avatars.githubusercontent.com/u/5827823?v=4"></div><div class="author-info__name text-center">kyren</div><div class="author-info__description text-center">huluo的技术博客</div><div class="follow-button"><a target="_blank" rel="noopener" href="https://github.com/huluo666">Follow Me</a></div><hr><div class="author-info-articles"><a class="author-info-articles__archives article-meta" href="/archives"><span class="pull-left">文章</span><span class="pull-right">239</span></a><a class="author-info-articles__tags article-meta" href="/tags"><span class="pull-left">标签</span><span class="pull-right">41</span></a><a class="author-info-articles__categories article-meta" href="/categories"><span class="pull-left">分类</span><span class="pull-right">29</span></a></div><hr><div class="author-info-links"><div class="author-info-links__title text-center">Links</div><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:9090/">Jira</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://192.168.2.212:8090/">Confluence</a><a class="author-info-links__name text-center" target="_blank" rel="noopener" href="http://bloc.leniugame.com/">Leniu</a></div></div></div><div id="content-outer"><div class="no-bg" id="top-container"><div id="page-header"><span class="pull-left"> <a id="site-name" href="/">Kyren's Blog</a></span><i class="fa fa-bars toggle-menu pull-right" aria-hidden="true"></i><span class="pull-right menus">   <a class="site-page" href="/">主页</a><a class="site-page" href="/essay">随笔</a><a class="site-page" href="/archives">归档</a><a class="site-page" href="/tags">标签</a><a class="site-page" href="/categories">分类</a><a class="site-page" href="/about">关于</a></span><span class="pull-right"><a class="site-page social-icon search"><i class="fa fa-search"></i><span> 搜索</span></a></span></div><div id="post-info"><div id="post-title">iOS谓词NSPredicate 筛选过滤</div><div id="post-meta"><time class="post-meta__date"><i class="fa fa-calendar" aria-hidden="true"></i> 2016-11-04</time><span class="post-meta__separator">|</span><i class="fa fa-inbox post-meta__icon" aria-hidden="true"></i><a class="post-meta__categories" href="/categories/iOS/">iOS</a></div></div></div><div class="layout" id="content-inner"><article id="post"><div class="article-container" id="post-content"><p>NSPredicate 筛选过滤</p>
<p>基本用法</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">1.创建NSPredicate（相当于创建一个过滤条件）</span><br><span class="line">NSPredicate *predicate = [NSPredicate predicateWithFormat:@&quot;过滤条件&quot;];</span><br><span class="line"></span><br><span class="line">2.判断指定的对象是否满足NSPredicate创建的过滤条件</span><br><span class="line">[predicate evaluateWithObject:person];</span><br><span class="line"></span><br><span class="line">3.过滤出符合条件的对象（返回所有符合条件的对象）</span><br><span class="line">NSArray *persons = [array filteredArrayUsingPredicate:predicate];</span><br></pre></td></tr></table></figure>

<p><code>+predicateWithFormat:来实际创建谓词。</code>可以使用单引号，双引号需要进行转义</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//基本的查询</span></span><br><span class="line"><span class="built_in">NSPredicate</span> *predicate;</span><br><span class="line"><span class="comment">//方法一：</span></span><br><span class="line">predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;name == &#x27;Herbie&#x27;&quot;</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">//方法二：</span></span><br><span class="line">predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;name == %@&quot;</span>, <span class="string">@&quot;Herbie&quot;</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">//方法三：%K表示key</span></span><br><span class="line">predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;%K == %@&quot;</span>, <span class="string">@&quot;name&quot;</span>, <span class="string">@&quot;Herbie&quot;</span>];</span><br><span class="line"><span class="type">BOOL</span> match = [predicate evaluateWithObject:car];</span><br><span class="line"><span class="built_in">NSLog</span>(<span class="string">@&quot;%s&quot;</span>, (match) ? <span class="string">&quot;YES&quot;</span> : <span class="string">&quot;NO&quot;</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">以上为对象属性匹配，如果数组中都是字符串如何匹配－－<span class="keyword">self</span></span><br><span class="line"><span class="built_in">NSArray</span> *array=[<span class="built_in">NSArray</span> arrayWithObjects: <span class="string">@&quot;abc&quot;</span>, <span class="string">@&quot;def&quot;</span>, <span class="string">@&quot;ghi&quot;</span>,<span class="string">@&quot;jkl&quot;</span>, <span class="literal">nil</span> <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSPredicate</span> *pre = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;SELF==&#x27;abc&#x27;&quot;</span>];</span><br><span class="line"><span class="built_in">NSArray</span> *array2 = [array filteredArrayUsingPredicate:pre];</span><br></pre></td></tr></table></figure>



<h5 id="1-比较运算符-gt-lt-x3D-x3D-gt-x3D-lt-x3D-x3D"><a href="#1-比较运算符-gt-lt-x3D-x3D-gt-x3D-lt-x3D-x3D" class="headerlink" title="1.比较运算符(&gt;,&lt;,&#x3D;&#x3D;,&gt;&#x3D;,&lt;&#x3D;,!&#x3D;)"></a>1.比较运算符(&gt;,&lt;,&#x3D;&#x3D;,&gt;&#x3D;,&lt;&#x3D;,!&#x3D;)</h5><p>可用于数值及字符串 例：@”number &gt; 100”</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSArray</span> *array = [<span class="built_in">NSArray</span> arrayWithObjects:@<span class="number">1</span>,@<span class="number">2</span>,@<span class="number">3</span>,@<span class="number">4</span>,@<span class="number">5</span>,@<span class="number">2</span>,@<span class="number">6</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSPredicate</span> *predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;SELF &gt;4&quot;</span>];</span><br><span class="line"><span class="built_in">NSArray</span> *fliterArray = [array filteredArrayUsingPredicate:predicate];</span><br><span class="line">[fliterArray enumerateObjectsWithOptions:<span class="built_in">NSEnumerationConcurrent</span> usingBlock:^(<span class="type">id</span>  _Nonnull obj, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> * _Nonnull stop) &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;fliterArray = %@&quot;</span>,obj);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>

<h5 id="2、运算符"><a href="#2、运算符" class="headerlink" title="2、运算符"></a>2、运算符</h5><h5 id="比较和逻辑运算符"><a href="#比较和逻辑运算符" class="headerlink" title="比较和逻辑运算符"></a>比较和逻辑运算符</h5><table>
<thead>
<tr>
<th>符号</th>
<th>意义</th>
</tr>
</thead>
<tbody><tr>
<td>&#x3D;&#x3D;</td>
<td>等于</td>
</tr>
<tr>
<td>&gt;</td>
<td>大于</td>
</tr>
<tr>
<td>&gt;&#x3D; (&#x3D;&gt;)</td>
<td>大于或等于</td>
</tr>
<tr>
<td>&lt;</td>
<td>小于</td>
</tr>
<tr>
<td>&lt;&#x3D; (&#x3D;&lt;)</td>
<td>小于或等于</td>
</tr>
<tr>
<td>!&#x3D; (&lt;&gt;)</td>
<td>不等于</td>
</tr>
</tbody></table>
<p>括号和逻辑运算AND、OR、NOT或者C样式的等效表达式&amp;&amp;、||、!</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">//输出完整的信息，在整个数组里寻找匹配的结果</span><br><span class="line">predicate = [NSPredicate predicateWithFormat:@&quot;age &gt; 100&quot;];</span><br><span class="line">NSArray *results = [self.cars filteredArrayUsingPredicate: predicate];</span><br><span class="line">NSLog (@&quot;%@&quot;, results);</span><br><span class="line"></span><br><span class="line">//谓词字符窜还支持C语言中一些常用的运算符</span><br><span class="line">predicate = [NSPredicate predicateWithFormat:@&quot;(age &gt; 50) AND (age &lt; 100)&quot;];</span><br><span class="line">results = [self.cars filteredArrayUsingPredicate: predicate];</span><br><span class="line">NSLog (@&quot;C语言中一些常用的运算符~~~~~~~%@&quot;, results);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">//比较字符串的大小</span><br><span class="line">predicate = [NSPredicate predicateWithFormat:@&quot;name &lt; &#x27;Newton&#x27;&quot;];</span><br></pre></td></tr></table></figure>



<h6 id="2-1-范围运算符-IN、BETWEEN"><a href="#2-1-范围运算符-IN、BETWEEN" class="headerlink" title="2.1.范围运算符(IN、BETWEEN)"></a>2.1.范围运算符(IN、BETWEEN)</h6><p>@”number BETWEEN {1,5}” @”address IN {‘shanghai’,’beijing’}”</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSArray</span> *array = [<span class="built_in">NSArray</span> arrayWithObjects:@<span class="number">1</span>,@<span class="number">2</span>,@<span class="number">3</span>,@<span class="number">4</span>,@<span class="number">5</span>,@<span class="number">2</span>,@<span class="number">6</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSPredicate</span> *predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;SELF in &#123;2,5&#125;&quot;</span>]; <span class="comment">//找到 in 的意思是array中&#123;2,5&#125;的元素</span></span><br><span class="line"><span class="comment">//NSPredicate *predicate = [NSPredicate predicateWithFormat:@&quot;SELF BETWEEN &#123;2,5&#125;&quot;];</span></span><br><span class="line"><span class="built_in">NSArray</span> *fliterArray = [array filteredArrayUsingPredicate:predicate];</span><br><span class="line">[fliterArray enumerateObjectsWithOptions:<span class="built_in">NSEnumerationConcurrent</span> usingBlock:^(<span class="type">id</span>  _Nonnull obj, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> * _Nonnull stop) &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;fliterArray = %@&quot;</span>,obj);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>

<h5 id="3-字符串本身-SELF"><a href="#3-字符串本身-SELF" class="headerlink" title="3.字符串本身(SELF)"></a>3.字符串本身(SELF)</h5><blockquote>
<p>类似于SQL语句<br>NOT 不是<br>SELF 代表字符串本身<br>IN 范围运算符<br>那么NOT (SELF IN %@) 意思就是：不是这里所指定的字符串的值</p>
</blockquote>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">NSArray</span> *placeArray = [<span class="built_in">NSArray</span> arrayWithObjects:<span class="string">@&quot;Shanghai&quot;</span>,<span class="string">@&quot;Hangzhou&quot;</span>,<span class="string">@&quot;Beijing&quot;</span>,<span class="string">@&quot;Macao&quot;</span>,<span class="string">@&quot;Taishan&quot;</span>, <span class="literal">nil</span>];</span><br><span class="line"><span class="built_in">NSPredicate</span> *predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;SELF == &#x27;Beijing&#x27;&quot;</span>];</span><br><span class="line"><span class="built_in">NSArray</span> *tempArray = [placeArray filteredArrayUsingPredicate:predicate];</span><br><span class="line">[tempArray enumerateObjectsUsingBlock:^(<span class="type">id</span>  _Nonnull obj, <span class="built_in">NSUInteger</span> idx, <span class="type">BOOL</span> * _Nonnull stop) &#123;</span><br><span class="line">    <span class="built_in">NSLog</span>(<span class="string">@&quot;obj == %@&quot;</span>,obj);</span><br><span class="line">&#125;];</span><br><span class="line"></span><br><span class="line"><span class="built_in">NSPredicate</span> * filterPredicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:@”NOT (SELF IN %@)”,filteredArray];</span><br><span class="line"><span class="comment">//    //过滤数组</span></span><br><span class="line"><span class="built_in">NSArray</span> * reslutFilteredArray = [dataArray filteredArrayUsingPredicate:filterPredicate];</span><br><span class="line"><span class="built_in">NSLog</span>(@”Reslut Filtered Array = %@”,reslutFilteredArray);</span><br></pre></td></tr></table></figure>

<h5 id="4字符串相关（BEGINSWITH、ENDSWITH、CONTAINS）"><a href="#4字符串相关（BEGINSWITH、ENDSWITH、CONTAINS）" class="headerlink" title="4字符串相关（BEGINSWITH、ENDSWITH、CONTAINS）"></a>4字符串相关（BEGINSWITH、ENDSWITH、CONTAINS）</h5><blockquote>
<p>@”name CONTAIN[cd] ‘ang’”  	 &#x2F;&#x2F;包含某个字符串<br>@”name BEGINSWITH[c] ‘sh’”     &#x2F;&#x2F;以某个字符串开头<br>@”name ENDSWITH[d] ‘ang’”      &#x2F;&#x2F;以某个字符串结束</p>
</blockquote>
<p><code>注:[c]不区分大小写[d]不区分发音符号即没有重音符号[cd]既不区分大小写，也不区分发音符号。</code></p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">NSArray *placeArray = [NSArray arrayWithObjects:@&quot;Shanghai&quot;,@&quot;Hangzhou&quot;,@&quot;Beijing&quot;,@&quot;Macao&quot;,@&quot;Taishan&quot;, nil];</span><br><span class="line">//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@&quot;SELF CONTAINS [cd] &#x27;an&#x27; &quot;];</span><br><span class="line">    NSPredicate *predicate1 = [NSPredicate predicateWithFormat:@&quot;SELF Beginswith [cd] &#x27;sh&#x27; &quot;];</span><br><span class="line"> NSArray *tempArray = [placeArray filteredArrayUsingPredicate:predicate1];</span><br><span class="line">    [tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) &#123;</span><br><span class="line">        NSLog(@&quot;obj == %@&quot;,obj);</span><br><span class="line">    &#125;];</span><br></pre></td></tr></table></figure>

<h5 id="5通配符：LIKE"><a href="#5通配符：LIKE" class="headerlink" title="5通配符：LIKE"></a>5通配符：LIKE</h5><blockquote>
<p>@”name LIKE[cd] ‘er’” &#x2F;&#x2F;代表通配符,Like也接受[cd]. @”name LIKE[cd] ‘???er’”</p>
<p>“*”：表示任意多个字符匹配</p>
<p>“?”：表示一个字符匹配</p>
</blockquote>
<figure class="highlight plaintext"><figcaption><span>c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">NSArray *placeArray = [NSArray arrayWithObjects:@&quot;Shanghai&quot;,@&quot;Hangzhou&quot;,@&quot;Beijing&quot;,@&quot;Macao&quot;,@&quot;Taishan&quot;, nil];</span><br><span class="line">    NSPredicate *predicate = [NSPredicate predicateWithFormat:@&quot;SELF  like &#x27;*ai*&#x27; &quot;];</span><br><span class="line"></span><br><span class="line">NSArray *tempArray = [placeArray filteredArrayUsingPredicate:predicate];</span><br><span class="line">[tempArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) &#123;</span><br><span class="line">    NSLog(@&quot;obj == %@&quot;,obj);</span><br><span class="line">&#125;];</span><br></pre></td></tr></table></figure>

<h5 id="6正则表达式"><a href="#6正则表达式" class="headerlink" title="6正则表达式"></a>6正则表达式</h5><p>MATCHES例：</p>
<p>NSString *regex &#x3D; @”^A.+e$”; &#x2F;&#x2F;以A开头，e结尾</p>
<p> @”name MATCHES %@”,regex (还是用于其他的正则表达式)</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">NSString *regex = @&quot;^A.+e$&quot;;   //以A开头，e结尾  @&quot;name MATCHES %@&quot;,regex</span><br><span class="line">  NSPredicate *presdicate =[NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, regex];</span><br><span class="line">  NSString *content = @&quot;Alkdjflse&quot;;</span><br><span class="line"> BOOL result = [presdicate evaluateWithObject:content];</span><br><span class="line">  NSLog(@&quot;%d&quot;,result);</span><br><span class="line"></span><br><span class="line"> NSPredicate *exists = [NSPredicate predicateWithFormat:</span><br><span class="line">                         @&quot;%K MATCHES[c] %@&quot;, key, value];</span><br></pre></td></tr></table></figure>

<p>其它</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">// 判断首个字符是否为字母</span><br><span class="line">- (BOOL)isStartWithWord &#123;</span><br><span class="line">  NSString *regex = @&quot;[A-Za-z]+&quot;;</span><br><span class="line">  NSPredicate *predicate = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, regex];</span><br><span class="line">  return [predicate evaluateWithObject:aString];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//用户名是否为字母和数字组成</span><br><span class="line">- (BOOL)isUserName</span><br><span class="line">&#123;</span><br><span class="line">  NSString *regex = @&quot;(^[A-Za-z0-9]&#123;3,20&#125;$)&quot;;</span><br><span class="line">  NSPredicate *pred = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, regex];</span><br><span class="line">  return [pred evaluateWithObject:self];</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">//密码是否合法</span><br><span class="line">NSString *regex = @&quot;(^[A-Za-z0-9]&#123;6,20&#125;$)&quot;;</span><br><span class="line">//邮箱是否合法</span><br><span class="line">NSString *regex = @&quot;[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]&#123;2,4&#125;&quot;;</span><br><span class="line">//url是否合法</span><br><span class="line">NSString *regex = @&quot;http(s)?:\\/\\/([\\w-]+\\.)+[\\w-]+(\\/[\\w- .\\/?%&amp;=]*)?&quot;;</span><br></pre></td></tr></table></figure>



<p>多规则</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">- (BOOL)isTelephone</span><br><span class="line">&#123;</span><br><span class="line">    NSString * MOBILE = @&quot;^1(3[0-9]|5[0-35-9]|8[025-9])\\d&#123;8&#125;$&quot;;</span><br><span class="line">    NSString * CM = @&quot;^1(34[0-8]|(3[5-9]|5[017-9]|8[278])\\d)\\d&#123;7&#125;$&quot;;</span><br><span class="line">    NSString * CU = @&quot;^1(3[0-2]|5[256]|8[56])\\d&#123;8&#125;$&quot;;</span><br><span class="line">    NSString * CT = @&quot;^1((33|53|8[09])[0-9]|349)\\d&#123;7&#125;$&quot;;</span><br><span class="line">    NSString * PHS = @&quot;^0(10|2[0-5789]|\\d&#123;3&#125;)\\d&#123;7,8&#125;$&quot;;</span><br><span class="line">    NSPredicate *regextestmobile = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, MOBILE];</span><br><span class="line">    NSPredicate *regextestcm = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, CM];</span><br><span class="line">    NSPredicate *regextestcu = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, CU];</span><br><span class="line">    NSPredicate *regextestct = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, CT];</span><br><span class="line">    NSPredicate *regextestphs = [NSPredicate predicateWithFormat:@&quot;SELF MATCHES %@&quot;, PHS];</span><br><span class="line"></span><br><span class="line">    return  [regextestmobile evaluateWithObject:self]   ||</span><br><span class="line">            [regextestphs evaluateWithObject:self]      ||</span><br><span class="line">            [regextestct evaluateWithObject:self]       ||</span><br><span class="line">            [regextestcu evaluateWithObject:self]       ||</span><br><span class="line">            [regextestcm evaluateWithObject:self];</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>



<p>查询字字典，模型属性</p>
<figure class="highlight objectivec"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1 字符串中查出保函某个字节</span></span><br><span class="line">   <span class="built_in">NSArray</span>  *array =@[<span class="string">@&quot;123&quot;</span>, <span class="string">@&quot;234&quot;</span> , <span class="string">@&quot;345&quot;</span>];</span><br><span class="line">   <span class="built_in">NSPredicate</span> *predicate = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;SELF contains [cd] %@&quot;</span>, <span class="string">&quot;2&quot;</span>];</span><br><span class="line">   <span class="built_in">NSArray</span> *filterdArray1 = [array filteredArrayUsingPredicate:predicate];</span><br><span class="line">   <span class="built_in">NSLog</span>(<span class="string">@&quot;%@&quot;</span>, filterdArray1);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">   <span class="comment">//2.查找封装model对象的数组，根据model的一个属性</span></span><br><span class="line">   <span class="built_in">NSPredicate</span> *predicate2 = [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;fileName == %@&quot;</span>, <span class="string">&quot;Ansel&quot;</span>];</span><br><span class="line">   <span class="built_in">NSArray</span> *filteredArray2 = [array filteredArrayUsingPredicate:predicate2];</span><br><span class="line">   <span class="built_in">NSLog</span>(<span class="string">@&quot;filteredArray2：%@&quot;</span>, filteredArray2);</span><br><span class="line"></span><br><span class="line">   <span class="comment">//3.查询数组中字典莫一个Key的值</span></span><br><span class="line">   <span class="built_in">NSArray</span> *array3 = @[ @&#123; <span class="string">@&quot;lastName&quot;</span> : <span class="string">@&quot;Turner&quot;</span> &#125;,</span><br><span class="line">                        @&#123; <span class="string">@&quot;firstName&quot;</span> : <span class="string">@&quot;Ben&quot;</span>, <span class="string">@&quot;lastName&quot;</span> : <span class="string">@&quot;Ballard&quot;</span>,</span><br><span class="line">                           <span class="string">@&quot;birthday&quot;</span>: <span class="string">@&quot;1972-03-24 10:45:32 +0600&quot;</span></span><br><span class="line">                           &#125;</span><br><span class="line">                   ];</span><br><span class="line">   <span class="built_in">NSPredicate</span> *predicate3 =</span><br><span class="line">   [<span class="built_in">NSPredicate</span> predicateWithFormat:<span class="string">@&quot;firstName like %@&quot;</span>, <span class="string">@&quot;firstName&quot;</span>];</span><br><span class="line">   <span class="built_in">NSArray</span> *filteredArray3 = [array3 filteredArrayUsingPredicate:predicate3];</span><br></pre></td></tr></table></figure>



<p>谓词去重</p>
<figure class="highlight plaintext"><figcaption><span>c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line">NSMutableSet *seenDates = [NSMutableSet set];</span><br><span class="line">NSPredicate *dupDatesPred = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) &#123;</span><br><span class="line">    Event *e = (Event*)obj;</span><br><span class="line">    BOOL seen = [seenDates containsObject:e.date];</span><br><span class="line">    if (!seen) &#123;</span><br><span class="line">        [seenDates addObject:e.date];</span><br><span class="line">    &#125;</span><br><span class="line">    return !seen;</span><br><span class="line">&#125;];</span><br><span class="line">NSArray *events = ... // This is your array which needs to be filtered</span><br><span class="line">NSArray *filtered = [events filteredArrayUsingPredicate:dupDatesPred];</span><br></pre></td></tr></table></figure>



<p>参考文档</p>
<p><a target="_blank" rel="noopener" href="http://nshipster.cn/nspredicate/">http://nshipster.cn/nspredicate/</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it?rq=1">https://stackoverflow.com/questions/805547/how-to-sort-an-nsmutablearray-with-custom-objects-in-it?rq=1</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/111866/best-way-to-remove-from-nsmutablearray-while-iterating?rq=1">https://stackoverflow.com/questions/111866/best-way-to-remove-from-nsmutablearray-while-iterating?rq=1</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/19373936/how-do-i-get-unique-values-from-an-array%E3%80%81">https://stackoverflow.com/questions/19373936/how-do-i-get-unique-values-from-an-array、</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objectivec">https://stackoverflow.com/questions/1025674/the-best-way-to-remove-duplicate-values-from-nsmutablearray-in-objectivec</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/4007427/removing-duplicates-from-array-in-objectivec">https://stackoverflow.com/questions/4007427/removing-duplicates-from-array-in-objectivec</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/19865936/finding-a-duplicate-numbers-in-an-array-and-then-counting-the-number-of-duplicat">https://stackoverflow.com/questions/19865936/finding-a-duplicate-numbers-in-an-array-and-then-counting-the-number-of-duplicat</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/5978574/removing-duplicates-from-nsmutablearray">https://stackoverflow.com/questions/5978574/removing-duplicates-from-nsmutablearray</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/20909709/removing-duplicate-profiles-loaded-from-an-xml-file-using-nspredicate">https://stackoverflow.com/questions/20909709/removing-duplicate-profiles-loaded-from-an-xml-file-using-nspredicate</a></p>
<p><a target="_blank" rel="noopener" href="https://stackoverflow.com/questions/43798167/to-get-duplicate-as-well-as-original-items-from-an-array-in-ios">https://stackoverflow.com/questions/43798167/to-get-duplicate-as-well-as-original-items-from-an-array-in-ios</a></p>
</div></article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta">文章作者: </span><span class="post-copyright-info"><a href="mailto:undefined">kyren</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta">文章链接: </span><span class="post-copyright-info"><a href="http://huluo666.gitee.io/2016/11/04/NSPredicate 筛选过滤/">http://huluo666.gitee.io/2016/11/04/NSPredicate 筛选过滤/</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta">版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a target="_blank" rel="noopener" href="https://creativecommons.org/licenses/by-nc-sa/4.0/">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来自 <a href="http://huluo666.gitee.io">Kyren's Blog</a>！</span></div></div><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/iOS/">iOS</a></div><nav id="pagination"><div class="prev-post pull-left"><a href="/2016/11/12/%E6%96%87%E5%AD%97%E9%97%AA%E7%83%81%E6%95%88%E6%9E%9C/"><i class="fa fa-chevron-left">  </i><span>文字闪烁效果</span></a></div><div class="next-post pull-right"><a href="/2016/11/03/Alfred%20web%E6%90%9C%E7%B4%A2%E9%85%8D%E7%BD%AE/"><span>Alfred web搜索配置</span><i class="fa fa-chevron-right"></i></a></div></nav></div></div><footer><div class="layout" id="footer"><div class="copyright">&copy;2022 By kyren</div><div class="framework-info"><span>驱动 - </span><a target="_blank" rel="noopener" href="http://hexo.io"><span>Hexo</span></a><span class="footer-separator">|</span><span>主题 - </span><a target="_blank" rel="noopener" href="https://github.com/Molunerfinn/hexo-theme-melody"><span>Melody</span></a></div><div class="footer_custom_text">hitokoto</div><div class="busuanzi"><script async src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script><span id="busuanzi_container_page_pv"><i class="fa fa-file"></i><span id="busuanzi_value_page_pv"></span><span></span></span></div></div></footer><i class="fa fa-arrow-up" id="go-up" aria-hidden="true"></i><script src="https://cdn.jsdelivr.net/npm/animejs@latest/lib/anime.min.js"></script><script src="https://cdn.jsdelivr.net/npm/jquery@latest/dist/jquery.min.js"></script><script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@latest/dist/jquery.fancybox.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-animate@latest/velocity.min.js"></script><script src="https://cdn.jsdelivr.net/npm/velocity-ui-pack@latest/velocity.ui.min.js"></script><script src="/js/utils.js?version=1.9.0"></script><script src="/js/fancybox.js?version=1.9.0"></script><script src="/js/sidebar.js?version=1.9.0"></script><script src="/js/copy.js?version=1.9.0"></script><script src="/js/fireworks.js?version=1.9.0"></script><script src="/js/transition.js?version=1.9.0"></script><script src="/js/scroll.js?version=1.9.0"></script><script src="/js/head.js?version=1.9.0"></script><script src="/js/search/local-search.js"></script><script>if(/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent)) {
  $('#nav').addClass('is-mobile')
  $('footer').addClass('is-mobile')
  $('#top-container').addClass('is-mobile')
}</script><div class="search-dialog" id="local-search"><div class="search-dialog__title" id="local-search-title">本地搜索</div><div id="local-input-panel"><div id="local-search-input"><div class="local-search-box"><input class="local-search-box--input" placeholder="搜索文章"></div></div></div><hr><div id="local-search-results"><div id="local-hits"></div><div id="local-stats"><div class="local-search-stats__hr" id="hr"><span>由</span> <a target="_blank" rel="noopener" href="https://github.com/wzpan/hexo-generator-search" style="color:#49B1F5;">hexo-generator-search</a>
 <span>提供支持</span></div></div></div><span class="search-close-button"><i class="fa fa-times"></i></span></div><div class="search-mask"></div></body></html>